package com.wxy.school.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wxy.school.common.Constant;
import com.wxy.school.common.R;
import com.wxy.school.dto.UserDto;
import com.wxy.school.entity.User;
import com.wxy.school.service.UserService;
import com.wxy.school.utils.BaseContext;
import com.wxy.school.utils.SMSUtils;
import com.wxy.school.utils.ValidateCodeUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;

/**
 * @author 王祥宇
 * @projectName school
 * @packageName com.wxy.school.controller
 * @data 2023/3/19 17:22
 * @description: TODO
 * @version: 1.0
 */

@RestController
@RequestMapping("school/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public R<User> login(HttpServletRequest httpServletRequest, @RequestBody User user){
        // 获取前端传过来的密码
        String password = user.getPassword();
        System.out.println(password);

        // 对传过来的密码进行MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        // 创建查询条件
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone, user.getPhone());
        // 调用Service层方法进行条件查询
        User user1 = userService.getOne(lambdaQueryWrapper);
        // 判断用户是否存在
        if(user1 == null){
            return R.error("登陆失败，用户不存在");
        }
        // 判断密码是否正确
        if (!user1.getPassword().equals(password)){
            return R.error("登陆失败，用户密码错误");
        }
        // 判断帐号状态是否正常
        if (user1.getStatus() == 0){
            return R.error("登陆失败，用户已被禁用");
        }


        // 存储用户信息到Session中
        httpServletRequest.getSession().setAttribute("employee", user1);
        //创建EmployeeDto对象，并将emp中数据拷贝给employeeDto
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user1, userDto);
        //使用UUID生成一个token并赋值给employeeDto对象中token属性
        userDto.setToken(UUID.randomUUID().toString());

        // 返回用户信息
        return R.success(userDto);
    }

    /**
     * @description: 发送验证码
     * @author: 王祥宇
     * @param: employee
     * @param: servletRequest
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @PostMapping("/loginWithPhone")
    public R<String> loginWithPhone(@RequestBody User user, HttpServletRequest servletRequest){

        if (StringUtils.isNotEmpty(user.getPhone())){
            //查询用户信息
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, user.getPhone());
            User user1 = userService.getOne(lambdaQueryWrapper);
            //判断用户是否存在
            if (user1 == null){
                User user2 = new User();
                user2.setPhone(user.getPhone());
                //生成用户初始密码
                //将加密后的用户密码存入employee对象
                user2.setPassword(DigestUtils.md5DigestAsHex("156832zxc@".getBytes()));
                //设置用户初始用户名
                user2.setName("用户" + System.currentTimeMillis());
                //设置初始头像
                user2.setAvatar("A019DEF14CD744B68E0D24F8DC1FE901.png");
                userService.save(user2);
            }
            //生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //发送短信
            SMSUtils.sendMessage(Constant.SIGN_NAME, Constant.TEMPLATE_CODE, user.getPhone(), code);
            log.info("code={}",code);

            //存储验证码
            servletRequest.getSession().setAttribute("code", code);
            return R.success("短信发送成功");

        }else {
            return R.error("短信发送失败");
        }
    }

    /**
     * @description: 对比验证码
     * @author: 王祥宇
     * @param: map
     * @param: servletRequest
     * @return: com.wxy.school.common.R<com.wxy.school.entity.Employee>
     */
    @PostMapping("/loginWithCode")
    public R<UserDto> loginWithCode(@RequestBody Map map, HttpServletRequest servletRequest){
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //获取保存好的验证码
        Object attribute = servletRequest.getSession().getAttribute("code");

        //对比验证码
        if (attribute != null && attribute.equals(code)){
            //查询用户信息
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(lambdaQueryWrapper);
            //创建EmployeeDto对象，并将emp中数据拷贝给employeeDto
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
            //使用UUID生成一个token并赋值给employeeDto对象中token属性
            userDto.setToken(UUID.randomUUID().toString());
            //返回用户信息
            return R.success(userDto);
        }else {
            return R.error("验证码错误");
        }
    }

    /**
     * @description: 根据手机号查询用户信息
     * @author: 王祥宇
     * @param: phone
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @GetMapping("/getByPhone/{phone}")
    public R<String> getByPhone(@PathVariable String phone){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(lambdaQueryWrapper);
        if (user == null){
            return R.error("该用户不存在，请检查手机号是否输入正确");
        }else {
            return R.success("success");
        }
    }

    /**
     * @description: 修改用户密码
     * @author: 王祥宇
     * @param: employee
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @PutMapping("/updateUserPassword")
    public R<String> updatePassword(@RequestBody User user){
        //将用户名存储到线程中
        BaseContext.setThreadLocal(user.getName());
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userService.updateById(user);
        return R.success("用户密码修改成功,请重新进行登录");
    }

    @GetMapping("/getById/{id}")
    public R<User> getById(@PathVariable Long id){
        User user = userService.getById(id);
        return R.success(user);
    }

    @PostMapping("/sendCode/{phone}")
    public R<String> sendCode(@PathVariable String phone, HttpServletRequest servletRequest){
        if (StringUtils.isNotEmpty(phone)){
            //生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //发送短信
            SMSUtils.sendMessage("智慧校园", "SMS_460575217", phone, code);
            log.info("code={}",code);

            //存储验证码
            servletRequest.getSession().setAttribute("code", code);
            return R.success("短信发送成功");
        }else {
            return R.error("手机号为空");
        }
    }

    @PostMapping("/compareCode")
    public R<User> compareCode(@RequestBody Map map, HttpServletRequest servletRequest){
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //获取用户id
        Long id = Long.parseLong(map.get("id").toString());
        //获取保存好的验证码
        Object attribute = servletRequest.getSession().getAttribute("code");
        //对比验证码
        if (attribute != null && attribute.equals(code)){
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getId, id);
            User user = userService.getOne(lambdaQueryWrapper);
            user.setPhone(phone);
            userService.updateById(user);
            //返回用户信息
            return R.success(user);
        }else {
            return R.error("验证码错误");
        }
    }
}
